package com.peng.test.jdk;

import static java.lang.System.currentTimeMillis;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

import org.jetbrains.annotations.NotNull;
import org.junit.Test;

/**
 * DelayQueueSample
 * <p>
 * Created on 2022/12/12
 *
 * @author lupeng
 */
public class DelayQueueSample {



    @Test
    public void t1() {
        DelayQueue<DelayRunTask> delayQueue = new DelayQueue<>();
        while (true) {
            try {
                DelayRunTask task = delayQueue.poll(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("poll success");
        }
    }

    static class DelayRunTask implements Delayed {

        private final long startTime = System.currentTimeMillis();

        private final long delayTime;

        public DelayRunTask(long delayTime) {
            this.delayTime = delayTime;
        }

        @Override
        public long getDelay(@NotNull TimeUnit unit) {
            return unit.convert((startTime + delayTime) - currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(@NotNull Delayed o) {
            return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
        }
    }
}
